package com.example.demo.service;

import com.example.demo.util.StoreUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Service
public class IdempotentService {

    public Map<String,String> createToken(){
        Map<String,String> result = new HashMap<>();

        String tokenName = RandomStringUtils.randomAlphanumeric(6);
        String tokenValue = RandomStringUtils.randomNumeric(10);
        result.put("tokenName",tokenName);
        result.put("tokenValue",tokenValue);

        StoreUtil.putValue(tokenName,tokenValue);

        return result;
    }

    public boolean checkToken(String tokenName, String tokenValue){
        if (tokenName==null || tokenValue==null){
            return false;
        }

        synchronized (this){
            if (tokenValue.equals(StoreUtil.getValue(tokenName))){
                StoreUtil.removeValue(tokenName);

                return true;
            }
        }

        return false;
    }
}
